import * as echarts from '../../ec-canvas/echarts';
var HttpUtil = require('../../utils/httpUtil.js');
const app = getApp();
var myColor1 = ['#21BF57', '#21BF57', '#56D0E3', '#56D0E3', '#F57474',]
var myColor = ['#38B0DE', '#38B0DE', '#38B0DE', '#38B0DE', '#38B0DE',]
var standerdLength = [100, 100, 100, 100, 100,]
var dayStanderdValues = []
var weekStanderdValues = []

var dayValue = []
var weekValue = []
var dayView = []
var weekView = []

function ecDay(chart) {

  var option = {

    //backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '标准摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [{
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          // barBorderRadius: 16,
          color: function (params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return dayStanderdValues[data.dataIndex]
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: standerdLength,
    }]
  };
  chart.setOption(option);

}

function ecDay1(chart) {
  var option = {

    //backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '实际摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [{
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          color: function (params) {
            let percentage = dayValue[params.dataIndex]
            let color = "#56D0E3"
            if (percentage < 50) {
              color = "#21BF57"
            }
            if (percentage >= 100) {
              color = "#F57474"
            }
            return color
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return dayView[data.dataIndex]
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: dayValue,
    }]
  };
  chart.setOption(option);
}


function ecWeek(chart) {

  var option = {

    //backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '标准摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [{
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          // barBorderRadius: 16,
          color: function (params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return weekStanderdValues[data.dataIndex]
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: standerdLength,
    }]
  };
  chart.setOption(option);

}

function ecWeek1(chart) {
  var option = {

    //backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '实际摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [{
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          color: function (params) {
            let percentage = weekValue[params.dataIndex]
            let color = "#56D0E3"
            if (percentage < 50) {
              color = "#21BF57"
            }
            if (percentage >= 100) {
              color = "#F57474"
            }
            return color
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return weekView[data.dataIndex]
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: weekValue,
    }]
  };
  chart.setOption(option);
}






Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    ecDay: {
      lazyLoad: true
    },
    ecDay1: {
      lazyLoad: true
    },
    ecWeek: {
      lazyLoad: true
    },
    ecWeek1: {
      lazyLoad: true
    },
  },
  swichNav: function (e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  bindChange: function (e) {

    var that = this;
    that.setData({ currentTab: e.detail.current });

  },


  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     dayValue = []
     weekValue = []
     dayView = []
     weekView = []
    this.ecDayComponent = this.selectComponent('#mychart-dom-day');
    this.ecDay1Component = this.selectComponent('#mychart-dom-day1');
    this.ecWeekComponent = this.selectComponent('#mychart-dom-week');
    this.ecWeek1Component = this.selectComponent('#mychart-dom-week1');
    var that = this;
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
        });
      }

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    let standardIntake = app.globalData.userInfo.standardIntake
    dayStanderdValues = []
    dayStanderdValues.push(standardIntake.energyCal+"千卡")
    dayStanderdValues.push(standardIntake.protein+"克")
    dayStanderdValues.push(standardIntake.fatAvg + "克")
    dayStanderdValues.push(standardIntake.carbohyMinGd + "克")
    dayStanderdValues.push(standardIntake.elementCa+"毫克")

    weekStanderdValues = []
    weekStanderdValues.push(Math.round(standardIntake.energyCal * 7 )+ "千卡")
    weekStanderdValues.push(Math.round(standardIntake.protein * 7 )+ "克")
    weekStanderdValues.push(Math.round(standardIntake.fatAvg * 7) + "克")
    weekStanderdValues.push(Math.round(standardIntake.carbohyMinGd * 7) + "克")
    weekStanderdValues.push(Math.round(standardIntake.elementCa * 7) + "毫克")


    let userId = app.globalData.userInfo.userId
    let url = app.globalData.serverPath + "/meal/getTodayAllIntakeByUserId?userId=" + userId;
     HttpUtil.GET(url).then((res) => {
      let intake=res.data.result
      console.log("当日数据", intake)
      dayView.push(intake.energy+"千卡")
      dayView.push(intake.proteins+"克")
      dayView.push(intake.fats + "克")
      dayView.push(intake.carbohydrates + "克")
      dayView.push(intake.calcium + "毫克")

      dayValue.push(Math.round(intake.energy / standardIntake.energyCal*100))
      dayValue.push(Math.round(intake.proteins / standardIntake.protein * 100))
      dayValue.push(Math.round(intake.fats / standardIntake.fatAvg * 100))
      dayValue.push(Math.round(intake.carbohydrates / standardIntake.carbohyMinGd * 100))
      dayValue.push(Math.round(intake.calcium / standardIntake.elementCa * 100))
      for (let i in dayValue) {
        if (dayValue[i] > 100) {
          dayValue[i] = 100
        }
      }

      that.ecDayComponent.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        ecDay(chart);
        return chart;
      });
      that.ecDay1Component.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        ecDay1(chart);
        return chart;
      });

    }).catch((errMsg) => {
      console.log("查询每日摄入量失败", errMsg);
    });



    url = app.globalData.serverPath + "/meal/getWeekIntakeByUserId?userId=" + userId;
    HttpUtil.GET(url).then((res) => {
      let intake = res.data.result
      console.log("当周数据", intake)
      weekView.push(intake.energy + "千卡")
      weekView.push(intake.proteins + "克")
      weekView.push(intake.fats + "克")
      weekView.push(intake.carbohydrates + "克")
      weekView.push(intake.calcium + "毫克")

      weekValue.push(Math.round(intake.energy / (standardIntake.energyCal*7) * 100))
      weekValue.push(Math.round(intake.proteins / (standardIntake.protein * 7) * 100))
      weekValue.push(Math.round(intake.fats / (standardIntake.fatAvg * 7) * 100))
      weekValue.push(Math.round(intake.carbohydrates / (standardIntake.carbohyMinGd * 7) * 100))
      weekValue.push(Math.round(intake.calcium / (standardIntake.elementCa * 7) * 100))
      for (let i in weekValue) {
        if (weekValue[i] > 100) {
          weekValue[i] = 100
        }
      }


      that.ecWeekComponent.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        ecWeek(chart);
        return chart;
      });
      that.ecWeek1Component.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        ecWeek1(chart);
        return chart;
      });

    }).catch((errMsg) => {
      console.log("查询每周摄入量失败", errMsg);
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})